#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cassert>
#include <vector>
#include "Task.hpp"

#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

#define PROCESS_NUM 5

int waitCommand(int waitFd, bool& quit)
{
    uint32_t command = 0; // 要接受命令
    ssize_t s = read(waitFd, &command, sizeof(command));
    assert(s == sizeof(uint32_t));
    if (s == 0) // 如果没有读到数据就代表写端关闭了，此时子进程就要退出
    {
        quit = true;
        return -1;
    }
    return command;
}

void sendAndWakeup(pid_t who, int fd, uint32_t command)
{
    write(fd, &command, sizeof (command));
    cout << "call process, pid: " << who << " execute: " << desc[command] << " through fd: " << fd << endl;
}

int main()
{
    load(); // 加载要执行的任务
    vector<pair<pid_t, int>> slots; // pid : pipefd 创建子进程pid和读端的键值对数组
    // 创建多个进程
    for (int i = 0; i < PROCESS_NUM; i++)
    {
        // 创建管道
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;

        pid_t id = fork();
        assert(id != -1);

        // 子进程读取
        if (id == 0)
        {
            // child
            // 关闭写端
            close(pipefd[1]);
            while (true)
            {
                // pipefd[0]
                // 等命令
                bool quit = false;
                int command = waitCommand(pipefd[0], quit); // 如果写端不发消息就阻塞
                if (quit) break; // quit改为true表示要退出
                // 执行命令
                if (command >= 0 && command < handlerSize())
                {
                    callbacks[command](); // 拿到什么指令就执行对应的方法
                }
                else
                {
                    cout << "非法command" << endl;
                }
            }
            exit(1);
        }
        // father
        // 关闭读端
        close(pipefd[0]);
        slots.push_back(pair<pid_t, int>(id, pipefd[1]));
    }

    // 父进程派发任务
    // 生成随机数
    srand((unsigned int)time(nullptr) ^ getpid() ^ 0x12345); // 让随机数更随机
    while (true)
    {
        // 随机发送一个指令
        int command = rand()%handlerSize();
        // 选择进程
        int choice = rand()%slots.size();
        // 布置任务
        sendAndWakeup(slots[choice].first, slots[choice].second, command);
        sleep(1);

        // int select;
        // int command;
        // cout << "#######################################" << endl;
        // cout << "## 1. show function  2. send command ##" << endl;
        // cout << "#######################################" << endl;
        // cout << "Please Select> ";
        // cin >> select;
        // if (select == 1) showHandler();
        // else if (select == 2)
        // {
        //     cout << "Enter Your Command> ";
        //     // 选择任务
        //     cin >> command;
        //     // 选择进程
        //     int choice = rand()%slots.size();
        //     // 布置任务
        //     sendAndWakeup(slots[choice].first, slots[choice].second, command);
        // }
    }

    // 关闭fd，结束所有进程
    for (const auto slot : slots)
    {
        close(slot.second);
    }

    // 回收所有的子进程信息
    for (const auto slot : slots)
    {
        waitpid(slot.first, nullptr, 0);
    }

    return 0;
}